﻿using BluetoothMachine.Domains;
using BluetoothMachine.GlobalStatics;
using BluetoothMachine.Models;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Prism.Commands;
using System.Windows.Controls;
using System.Threading;
using BluetoothMachine.ExpandHelper;
using System.Collections;
using System.Windows;
using BluetoothMachine.Protocols;
using log4net;
using System.Windows.Media;
using MaterialDesignThemes.Wpf;
using BluetoothMachine.Views.DialogHosts;
using BluetoothMachine.ViewModels.DialogHostsModel;

namespace BluetoothMachine.ViewModels
{
    public class MainWindowViewModel
    {
        private CancellationTokenSource _threadToken;
        private HomeGlobal _homeGlobal;
        public ParameterConfigurationGlobal ParameterGlobal { get; set; }
        public MainWindowViewModel()
        {
            _threadToken = new CancellationTokenSource();
            ParameterGlobal = ServiceDiscovery.ResolveSingleton<ParameterConfigurationGlobal>();
            _homeGlobal = ServiceDiscovery.ResolveSingleton<HomeGlobal>();
            ParameterGlobal.ContentList.AddRange(ServiceDiscovery.ResolvePage(Enums.AuthorityType.管理员));
        }

        private int _selectedItemObject;

        public int SelectedItemObject
        {
            get { return _selectedItemObject; }
            set {
                _selectedItemObject = value;
                if (_selectedItemObject != 0 && _selectedItemObject != 4) DialogHost.Show(new LoginDialogs() { DataContext = new LoginDialogsViewModel() }, "RootDialog").ConfigureAwait(false);
            }
        }


        public DelegateCommand<Button> StartRun => new DelegateCommand<Button>(sender =>
        {
            ILog log = LogManager.GetLogger("message");
            sender.IsEnabled = false;
            var device = ServiceDiscovery.ResolveSingleton<DeviceManagementGlobal>();
            var para = ServiceDiscovery.ResolveSingleton<ParameterConfigurationGlobal>();
            if (sender.Content.ToString() == "    运  行    ")
            {
                if (_homeGlobal.ScramToken.Token.IsCancellationRequested) _homeGlobal.ScramToken = new CancellationTokenSource();
                if (_threadToken.Token.IsCancellationRequested) _threadToken = new CancellationTokenSource();
                if (device.ConnectionTcp())
                {
                    log.Info("开始运行\r\n");
                    Task.Run(async () =>
                    {
                        while (!_threadToken.Token.IsCancellationRequested)
                        {
                            var ionum = LTDMC.dmc_read_inport(LTDMC.CardID[0], 0);
                            var qiya = LTDMC.dmc_read_inbit(LTDMC.CardID[1], 15);
                            if ((ionum & 0b0000_0000_0000_0000_0000_0000_0000_0001) != 0)
                            {
                                //急停
                                LTDMC.dmc_emg_stop(LTDMC.CardID[0]);
                                LTDMC.dmc_emg_stop(LTDMC.CardID[1]);
                                if (!_homeGlobal.ScramToken.Token.IsCancellationRequested) _homeGlobal.ScramToken.Cancel();
                                _homeGlobal.MessagesList[0].Insert(0, new RunMessage() { RunTime = DateTime.Now.ToString("T"), Message = "触发急停", MessageForeground = Brushes.Red });
                                //return;
                            }
                            if ((ionum & 0b0000_0000_0000_0000_0000_0000_0000_0010) == 0)
                            {
                                _homeGlobal.MessagesList[0].Insert(0, new RunMessage() { RunTime = DateTime.Now.ToString("T"), Message = "复位启动，开始回原点", MessageForeground = Brushes.Black });
                                #region Z轴回原点
                                await Task.WhenAll(
                                    Task.Run(() => MotorMovements.HomeMove(LTDMC.CardID[0], 2)),
                                    Task.Run(() => MotorMovements.HomeMove(LTDMC.CardID[0], 5)),
                                    Task.Run(() => MotorMovements.HomeMove(LTDMC.CardID[1], 0)),
                                    Task.Run(() => MotorMovements.HomeMove(LTDMC.CardID[1], 3)),
                                    Task.Run(() => MotorMovements.HomeMove(LTDMC.CardID[1], 6)));
                                _homeGlobal.MessagesList[0].Insert(0, new RunMessage() { RunTime = DateTime.Now.ToString("T"), Message = "Z轴回原点完成", MessageForeground = Brushes.Black });
                                #endregion
                                #region XY轴回原点
                                await Task.WhenAll(
                                    Task.Run(() => MotorMovements.HomeMove(LTDMC.CardID[0], 0)),
                                    Task.Run(() => MotorMovements.HomeMove(LTDMC.CardID[0], 3)),
                                    Task.Run(() => MotorMovements.HomeMove(LTDMC.CardID[0], 6)),
                                    Task.Run(() => MotorMovements.HomeMove(LTDMC.CardID[1], 1)),
                                    Task.Run(() => MotorMovements.HomeMove(LTDMC.CardID[1], 4)),
                                    //---------------------------//
                                    Task.Run(() => MotorMovements.HomeMove(LTDMC.CardID[0], 1)),
                                    Task.Run(() => MotorMovements.HomeMove(LTDMC.CardID[0], 4)),
                                    Task.Run(() => MotorMovements.HomeMove(LTDMC.CardID[0], 7)),
                                    Task.Run(() => MotorMovements.HomeMove(LTDMC.CardID[1], 2)),
                                    Task.Run(() => MotorMovements.HomeMove(LTDMC.CardID[1], 5)));
                                _homeGlobal.MessagesList[0].Insert(0, new RunMessage() { RunTime = DateTime.Now.ToString("T"), Message = "X-Y轴回原点完成", MessageForeground = Brushes.Black });
                                #endregion
                                for (int i = 0; i < 16; i++)
                                {
                                    LTDMC.dmc_set_position(LTDMC.CardID[i > 7 ? 1 : 0], (ushort)(i % 8), 0);
                                }
                                for (int i = 1; i < 6; i++)
                                {
                                    try
                                    {
                                        var eio = device.ConnectList.FirstOrDefault(x => x.Index == i & x.CommType == false);
                                        //01-0F-00-00-00-10-02-00-00-E2-20
                                        eio.Write(new byte[] { 0x01, 0x0F, 0, 0, 0, 0x10, 0x02, 0, 0, 0xE2, 0x20 });
                                        Thread.Sleep(30);
                                        _ = eio.Read();
                                    }
                                    catch (Exception ex)
                                    {
                                        _homeGlobal.MessagesList[0].Insert(0, new RunMessage() { RunTime = DateTime.Now.ToString("T"), Message = $"扩展IO控制异常：{ex.Message}", MessageForeground = Brushes.Red });
                                    }
                                }
                                _homeGlobal.MessagesList[0].Insert(0, new RunMessage() { RunTime = DateTime.Now.ToString("T"), Message = "开始轴卡复位", MessageForeground = Brushes.Black });
                                LTDMC.dmc_download_configfile(LTDMC.CardID[0], FixedParameter.LTDMC38000);
                                LTDMC.dmc_download_configfile(LTDMC.CardID[1], FixedParameter.LTDMC38001);
                                MotorMovements.BackOrigin();
                                _homeGlobal.MessagesList[0].Insert(0, new RunMessage() { RunTime = DateTime.Now.ToString("T"), Message = "复位完成", MessageForeground = Brushes.Black });
                                _homeGlobal.MessagesList[0].Insert(0, new RunMessage() { RunTime = DateTime.Now.ToString("T"), Message = "执行Y轴待机位", MessageForeground = Brushes.Black });
                                MotorMovements.SetXSpeed(ParameterGlobal.ParameterModel.XSpeed * 180);
                                MotorMovements.SetYSpeed(ParameterGlobal.ParameterModel.YSpeed * 180);
                                MotorMovements.SetZSpeed(ParameterGlobal.ParameterModel.ZSpeed * 360);
                                await Task.WhenAll(
                                    Task.Run(() => MotorMovements.ShaftOperation(LTDMC.CardID[0], 1, (int)(610 / 0.02))),
                                    Task.Run(() => MotorMovements.ShaftOperation(LTDMC.CardID[0], 4, (int)(610 / 0.02))),
                                    Task.Run(() => MotorMovements.ShaftOperation(LTDMC.CardID[0], 7, (int)(610 / 0.02))),
                                    Task.Run(() => MotorMovements.ShaftOperation(LTDMC.CardID[1], 2, (int)(610 / 0.02))),
                                    Task.Run(() =>MotorMovements.ShaftOperation(LTDMC.CardID[1], 5, (int)(610 / 0.02))));
                                var eio1 = device.ConnectList.FirstOrDefault(x => x.Index == 1 & x.CommType == false);
                                eio1.Write(new ModbusRTU(15, true));
                                Thread.Sleep(30);
                                _ = eio1.Read();
                                _homeGlobal.MessagesList[0].Insert(0, new RunMessage() { RunTime = DateTime.Now.ToString("T"), Message = "Y轴待机位完成", MessageForeground = Brushes.Black });
                                continue;
                            }
                            if ((ionum & 0b0000_0000_0000_0000_0000_0000_0000_0100) == 0)
                            {
                                //1通道
                                TaskManagers.GetObject.Publish(new Services.Models.KeyTestModel()
                                {
                                    ZReturnCoordinate = ParameterGlobal.ParameterModel.ZReturnCoordinateOne,
                                    Passageway = 0,
                                    Station = new ushort[] { 0, 1 },
                                    RCCX = 0,
                                    RCCY = 1,
                                    RCCZ = 2,
                                    IntervalTime = 1000,
                                    CardID = new ushort[] { LTDMC.CardID[0] },
                                    AxleCard =new AxleCardModel() {
                                        CardID = LTDMC.CardID,
                                        ButtonLeft = 0,
                                        Button200Left = 1,
                                        ButtonRight = 2,
                                        Button200Right = 3,
                                        LEDLeft = 7,
                                        LEDRight = 8,
                                        Origin = 3,
                                        MovingPoint = 2,
                                        PairedCylinderLeft = 4,
                                        PairedCylinderRight = 5,
                                    },
                                });
                            }
                            if ((ionum & 0b0000_0000_0000_0000_0000_0000_0000_1000) == 0)
                            {
                                //2通道
                                TaskManagers.GetObject.Publish(new Services.Models.KeyTestModel()
                                {
                                    ZReturnCoordinate = ParameterGlobal.ParameterModel.ZReturnCoordinateTwo,
                                    Passageway = 1,
                                    Station = new ushort[] { 2, 3 },
                                    RCCX = 3,
                                    RCCY = 4,
                                    RCCZ = 5,
                                    IntervalTime = 1000,
                                    CardID = new ushort[] { LTDMC.CardID[0] },
                                    AxleCard = new AxleCardModel()
                                    {
                                        CardID = LTDMC.CardID,
                                        ButtonLeft = 4,
                                        Button200Left = 5,
                                        ButtonRight = 6,
                                        Button200Right = 7,
                                        LEDLeft = 9,
                                        LEDRight = 10,
                                        MovingPoint = 4,
                                        Origin = 5,
                                        PairedCylinderLeft = 6,
                                        PairedCylinderRight = 7,
                                    },
                                });
                            }
                            if ((ionum & 0b0000_0000_0000_0000_0000_0000_0001_0000) == 0)
                            {
                                //3通道
                                TaskManagers.GetObject.Publish(new Services.Models.KeyTestModel()
                                {
                                    ZReturnCoordinate = ParameterGlobal.ParameterModel.ZReturnCoordinateThree,
                                    Passageway = 2,
                                    Station = new ushort[] { 4, 5 },
                                    RCCX = 6,
                                    RCCY = 7,
                                    RCCZ = 8,
                                    IntervalTime = 1000,
                                    CardID = LTDMC.CardID,
                                    AxleCard = new AxleCardModel()
                                    {
                                        CardID = LTDMC.CardID,
                                        ButtonLeft = 8,
                                        Button200Left = 9,
                                        ButtonRight = 10,
                                        Button200Right = 11,
                                        LEDLeft = 11,
                                        LEDRight = 12,
                                        MovingPoint = 6,
                                        Origin = 7,
                                        PairedCylinderLeft = 8,
                                        PairedCylinderRight = 9,
                                    },
                                });
                            }
                            if ((ionum & 0b0000_0000_0000_0000_0000_0000_0010_0000) == 0)
                            {
                                //4通道
                                TaskManagers.GetObject.Publish(new Services.Models.KeyTestModel()
                                {
                                    ZReturnCoordinate = ParameterGlobal.ParameterModel.ZReturnCoordinateFour,
                                    Passageway = 3,
                                    Station = new ushort[] { 6, 7 },
                                    RCCX = 9,
                                    RCCY = 10,
                                    RCCZ = 11,
                                    IntervalTime = 1000,
                                    CardID = new ushort[] { LTDMC.CardID[1] },
                                    AxleCard = new AxleCardModel()
                                    {
                                        CardID = LTDMC.CardID,
                                        ButtonLeft = 12,
                                        Button200Left = 13,
                                        ButtonRight = 14,
                                        Button200Right = 15,
                                        LEDLeft = 13,
                                        LEDRight = 14,
                                        MovingPoint = 8,
                                        Origin = 9,
                                        PairedCylinderLeft = 10,
                                        PairedCylinderRight = 11,
                                    },
                                });
                            }
                            if ((ionum & 0b0000_0000_0000_0000_0000_0000_0100_0000) == 0)
                            {
                                //5通道
                                TaskManagers.GetObject.Publish(new Services.Models.KeyTestModel()
                                {
                                    ZReturnCoordinate = ParameterGlobal.ParameterModel.ZReturnCoordinateFive,
                                    Passageway = 4,
                                    Station = new ushort[] { 8, 9 },
                                    RCCX = 12,
                                    RCCY = 13,
                                    RCCZ = 14,
                                    IntervalTime = 1000,
                                    CardID = new ushort[] { LTDMC.CardID[1] },
                                    AxleCard = new AxleCardModel()
                                    {
                                        CardID = LTDMC.CardID,
                                        ButtonLeft = 0,
                                        Button200Left = 1,
                                        ButtonRight = 2,
                                        Button200Right = 3,
                                        LEDLeft = 15,
                                        LEDRight = 1,
                                        MovingPoint = 10,
                                        Origin = 11,
                                        PairedCylinderLeft = 12,
                                        PairedCylinderRight = 13,
                                    },
                                });
                            }
                            if (qiya == 1) {
                                LTDMC.dmc_emg_stop(LTDMC.CardID[0]);
                                LTDMC.dmc_emg_stop(LTDMC.CardID[1]);
                                if (!_homeGlobal.ScramToken.Token.IsCancellationRequested) _homeGlobal.ScramToken.Cancel();
                                _homeGlobal.MessagesList[0].Insert(0, new RunMessage() { RunTime = DateTime.Now.ToString("T"), Message = "气压过低", MessageForeground = Brushes.Red });
                                //return;
                            }
                            Thread.Sleep(10);
                        }
                    }, _threadToken.Token).ContinueWith(x => sender.Content = "    运  行    ");
                    sender.Content = "    停  止    ";
                }
                else
                {
                    sender.Content = "    运  行    ";
                }
            }
            else
            {
                _threadToken.Cancel();
                device.DisconnectTCP();
                sender.Content = "    运  行    ";
            }
            sender.IsEnabled = true;
        });
    }
}
